package com.wisdytech.linkdcs.equipment.action;

import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardHTableResult;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.enums.CollectionShowLevel;
import com.wisdytech.common.handler.ResourceMatchingService;
import com.wisdytech.common.thrift.api.LinkDCSService;
import com.wisdytech.common.thrift.service.ThriftClient;
import com.wisdytech.common.utils.DataTransformUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.common.utils.ExcelUtil;
import com.wisdytech.linkdcs.equipment.dto.EquipHistoryDataDTO;
import com.wisdytech.linkdcs.equipment.dto.EquipHistorySearchDTO;
import com.wisdytech.linkdcs.equipment.dto.EquipmentAuoAlarmDTO;
import com.wisdytech.linkdcs.equipment.model.AutoAlarmRecord;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.service.IEquipmentDataService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentMqService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentParamViewService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;
import com.wisdytech.linkdcs.equipment.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * <p>ClassName: EquipDataManageAction</p>
 * <p>Description: 数据管理action</p>
 * <p>Author: dailibo</p>
 * <p>Date: 2017-10-10</p>
 */
@Controller
@RequestMapping("/equipment/data")
public class EquipDataManageAction {
	
	
	private static Logger logger =LoggerFactory.getLogger(EquipDataManageAction.class);
    @Autowired
    private IEquipmentDataService equipmentDataService;
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;

    
    @Autowired
    private IEquipmentRegisteredService equipmenService;
    
    @Autowired
    private IEquipmentParamViewService equipmentParamViewService;
    
    @Resource
    ThriftClient thriftClient;
    
    /****演示代码*****/
    @Autowired
    private IEquipmentMqService iEquipmentMqService;
    
    
    /**
     * 
     * <p>Description: 实时数据</p>
     * @param model
     * @return
     */
    @RequestMapping("/real/index")
    public String realIndex(Model model, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "equipment/equipDataManage/real/index";
    }
    
    /**
     * 
     * <p>Description: 实时数据详情</p>
     * @param model
     * @return
     */
    @RequestMapping("/real/detail")
    public String realDetail(Model model,String id, HttpServletRequest httpRequest){
        model.addAttribute("level1", "设备管理");
        model.addAttribute("level2", "设备联机");
        model.addAttribute("level3", "设备数据管理");
        model.addAttribute("level4", "实时数据监控");
        //未有id 跳转首页
        if(StringUtils.isBlank(id)){
            return "index";
        }
        
        Equipment  equipment =
                equipmenService.getEquipmentRegisterById(id);
        
        if(null == equipment){
            return "index";
        }
        
        
        //获取隔日分析参数
       /* List<CollectionParam>  params=
                equipmentParamViewService.getEuipmentParamView(id, CollectionShowLevel.REAL.level);*/
        
        /*model.addAttribute("params", params);*/
        
        List<CollectionParam>  historys =
    			equipmentParamViewService.getEuipmentParamView(id, CollectionShowLevel.HISTORY.level);
        
        
        model.addAttribute("params", historys);
       //修改设备类别
        if(equipment.getModelType().equals("1")){
            equipment.setModelType("生产类");
        }
        if(equipment.getModelType().equals("2")){
            equipment.setModelType("环境类");
        }
        if(equipment.getModelType().equals("3")){
            equipment.setModelType("能源类");
        }
        if(equipment.getModelType().equals("4")){
            equipment.setModelType("检测类");
        }
        if(equipment.getModelType().equals("5")){
            equipment.setModelType("生产辅助类");
        }
       
        model.addAttribute("equipment", equipment);
        
        
        return "equipment/equipDataManage/real/detail";
    }
    
    /**
     * 
     * <p>Description: 历史数据查询</p>
     * @param model
     * @return
     */
    @RequestMapping("/history/index")
    public String historyIndex(Model model, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "equipment/equipDataManage/history/index";
    }
    
    /**
     * 
     * <p>Description: 告警历史</p>
     * @param model
     * @return
     */
    @RequestMapping("/alarm/index")
    public String alarmIndex(Model model, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "equipment/equipDataManage/alarm/history";
    }
    
    /**
     * 
     * <p>Description: 告警 历史详细</p>
     * @param model
     * @return
     */
    @RequestMapping("/alarm/detail/index")
    public String alarmDetail(Model model,String equipCode,String paramCode,String startTime,String endTime, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);

         if(StringUtils.isNotBlank(equipCode)){
            model.addAttribute("equipCode",equipCode);
        }else{
            model.addAttribute("equipCode","");
        }
        
        if(StringUtils.isNotBlank(paramCode)){
            model.addAttribute("paramCode",paramCode);
        }else{
            model.addAttribute("paramCode","");
        }
        if(StringUtils.isNotBlank(startTime)){
            model.addAttribute("startTime",startTime);
        }else{
            model.addAttribute("startTime","");
        }
        if(StringUtils.isNotBlank(endTime)){
            model.addAttribute("endTime",endTime);
        }else{
            model.addAttribute("endTime","");
        }     
        
        
        return "equipment/equipDataManage/alarm/detail";
    }
    
    
    @RequestMapping("/real/get.mvc")
    @ResponseBody
    public StandardTableResult<EquipmentDataVO> listRealEquipment(String eqCode,String modelCode,Filter filter){
        
        
         PageInfo<EquipmentDataVO>  realData=  equipmentDataService.listRealData(filter, eqCode, modelCode);
        
        return new StandardTableResult<EquipmentDataVO>(realData.getTotal(), realData.getList());
    }
    
    
    
    /**
     * 
     * <p>Description: 获取自动自动告警列表</p>
     * @return
     */
    @RequestMapping("/alarm/listAuto/get.mvc")
    @ResponseBody
    public StandardTableResult<EquipmentAutoAlarmVO> listAutoAlarm(Filter filter,EquipmentAuoAlarmDTO dto){
        
       
               PageInfo<EquipmentAutoAlarmVO>  lists = equipmentDataService.listAutoAlarm(filter, dto);
        StandardTableResult<EquipmentAutoAlarmVO> result =new StandardTableResult<>(lists.getTotal(), lists.getList());
        
        return result;
    }
    
    
    
    @RequestMapping("/alarm/listAutoDetail/get.mvc")
    @ResponseBody
    public StandardTableResult<EqAutoAlarmDetailVO> listAutoAlarmDetail(Filter filter ,String equipCode,String paramCode,String startTime,String endTime){
        
        
        PageInfo<AutoAlarmRecord>  pageInfo =
                equipmentDataService.listAutoAlarmDetail(filter, equipCode, paramCode,startTime,endTime);
        
        List<AutoAlarmRecord> dataList=
                        pageInfo.getList();
        List<EqAutoAlarmDetailVO> voList=new ArrayList<>();
        //数据转换
        for(AutoAlarmRecord record : dataList){
            voList.add(DataTransformUtil.changeAlarmDetailVO(record));
        }
        
        return new StandardTableResult<>(pageInfo.getTotal(), voList);
    }
    
    
    /**
     * 
     * <p>Description: 获取设备实时分析参数值</p>
     * @param id
     * @return
     */
    @RequestMapping("/real/param/detail")
    @ResponseBody
    public StandardResult getEquipmentRealParamValue(String id){

        //获取实时参数
        List<CollectionParam>  params=
                equipmentParamViewService.getEuipmentParamView(id, CollectionShowLevel.REAL.level);
        
        EquipmentRealDataVO realData=
                equipmentDataService.listRealData(id, params);
        /*****演示代码添加数据*******/
//        iEquipmentMqService.addTest("real/param/detail/"+id, JSON.toJSONString(realData));
        //EquipmentRealDataVO realData = iEquipmentMqService.getTest("real/param/detail/"+id);
        /*EquipmentRealDataVO realData = new EquipmentRealDataVO();
        realData.setTime(System.currentTimeMillis());
        String data = iEquipmentMqService.getTest("real/param/detail/"+id);
        //List<EquipmentRealDataDetailVO> list = JSONObject.parseArray(data,EquipmentRealDataDetailVO.class);
        //realData.setParamReal(list);
        realData = JSON.parseObject(data,EquipmentRealDataVO.class);*/
        return StandardResult.getSuccessResult(realData);
    }
    
    @RequestMapping("/history/param/list")
    @ResponseBody
    public StandardResult getEquipmentHistoryParam(String id) {
    	List<CollectionParam>  historys =
    			equipmentParamViewService.getEuipmentParamView(id, CollectionShowLevel.HISTORY.level);
    	
    	return StandardResult.getSuccessResult(historys);
    }
    
    /**
     * 
     * <p>Description: 获取设备历史分析参数值</p>
     * @param equipmentId  设备id
     * @param paramId 参数id
     * @return
     */
    @RequestMapping("/history/param/detail")
    @ResponseBody
    public StandardResult getEquipmentHistoryParamValue(String equipCode,String paramId) throws ParseException{
    	
        if(StringUtils.isBlank(paramId)){
            return StandardResult.getFailResult();
        }

        List<String> params=new ArrayList<String>();
        List<Double> datas=new ArrayList<Double>();
        EquipHistoryDataDTO result =new EquipHistoryDataDTO();

        EquipHistorySearchDTO dto=new EquipHistorySearchDTO();
        dto.setEqId(equipCode);
        dto.setParamId(paramId);
        long endTime=System.currentTimeMillis();
        long startTime =endTime-1000L*3600L*24L;
        dto.setStartTime(DateUtil.getDefaultDateStr(new Date(startTime)));
        dto.setEndTime(DateUtil.getDefaultDateStr(new Date(endTime)));

        List<EquipmentHistoryDataVO> dataTest=  equipmentDataService.listHistoryDetail(dto);
        for (EquipmentHistoryDataVO vo:dataTest) {
            params.add(DateUtil.getDefaultDateStr(vo.getDate()));
            datas.add(Double.parseDouble(vo.getValue()));
        }
        result.setData(datas);
        result.setParam(params);
        return StandardResult.getSuccessResult(result);

        
    }
    
    @RequestMapping("/history/listDetail/get.mvc")
    @ResponseBody
    public List<EquipmentHistoryDataVO> listHistoryDetail(EquipHistorySearchDTO dto) throws ParseException {
        //分页查找对象
        List<EquipmentHistoryDataVO> result =
    			equipmentDataService.listHistoryDetail(dto);
        return result;
    }

    /**
     * <p>Description: 导出告警历史明细信息</p>
     * @param request 请求对象
     * @param response 返回对象
     * @throws Exception 异常
     */
    @RequestMapping(value="/exportHistoryRecord/export.mvc")
    public void exportHistoryRecord(HttpServletRequest request, HttpServletResponse response, Filter filter) throws Exception {
        SimpleDateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String[] columnNames = null;
        String[] fileNames = null;
        String fileName = "告警历史明细信息";
        String equipId = request.getParameter("equipId");
        String paramId = request.getParameter("paramId");
        String startTime="";
        String endTime="";
        filter.setSize(65535);
        PageInfo<AutoAlarmRecord> records;
        records =  equipmentDataService.listAutoAlarmDetail(filter, equipId, paramId,startTime, endTime);
        List<AutoAlarmRecord> recordList=records.getList();
        String finalFileName = null;  
        final String userAgent = request.getHeader("USER-AGENT"); 
        if(StringUtils.contains(userAgent, "MSIE")){
            //IE浏览器  
            finalFileName = URLEncoder.encode(fileName,"UTF8");  
        }else {
            finalFileName = fileName;
        }
        columnNames = new String[] { "设备编号", "工序", "设备名称", "告警参数名称", "参数数据", "时间", "告警名称"};
        fileNames = new String[] {"equipCode", "operationName", "equipName","paramName","alarmValue","createDate","alarmName"};
        ExcelUtil.exportExcel(response, recordList, AutoAlarmRecord.class, columnNames, fileNames,
                finalFileName + dateFormat.format(new Date()));
    }
    
    /**
     * <p>Description: 导出告警历史信息</p>
     * @param request 请求对象
     * @param response 返回对象
     * @throws Exception 异常
     */
    @RequestMapping(value="/exportHistory/export.mvc")
    public void exportHistory(HttpServletRequest request, HttpServletResponse response, Filter filter) throws Exception {
        SimpleDateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String[] columnNames = null;
        String[] fileNames = null;
        String fileName = "告警历史信息";
        String code = request.getParameter("code");
        String name = request.getParameter("name");
        String paramCode = request.getParameter("paramCode");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        EquipmentAuoAlarmDTO dto = new EquipmentAuoAlarmDTO();
        dto.setCode(code);
        dto.setName(name);
        dto.setParamCode(paramCode);
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        filter.setSize(65535);
        PageInfo<EquipmentAutoAlarmVO> historys;
        historys = equipmentDataService.listAutoAlarm(filter, dto);
        List<EquipmentAutoAlarmVO> historyList=historys.getList();
        String finalFileName = null;  
        final String userAgent = request.getHeader("USER-AGENT"); 
        if(StringUtils.contains(userAgent, "MSIE")){
            //IE浏览器  
            finalFileName = URLEncoder.encode(fileName,"UTF8");  
        }else {
            finalFileName = fileName;
        }
        columnNames = new String[] { "类别编号", "设备编号", "工序", "设备名称", "告警参数名称", "告警次数"};
        fileNames = new String[] {"modelCode", "equipmentCode", "operationName","equipmentName","paramName","count"};
        ExcelUtil.exportExcel(response, historyList, EquipmentAutoAlarmVO.class, columnNames, fileNames,
                finalFileName + dateFormat.format(new Date()));
    }
    
     
}
